<template>
  <div>
    <h3 style="margin: 10px" v-show="column.label">{{ column.label }}</h3>
    <draggable
      :class="['widget-form-table__content', 'vertical']"
      :list="column.children.column"
      :group="{ name: 'form' }"
      ghost-class="ghost"
      :animation="200"
      handle=".widget-form-table__item"
      @add="handleWidgetTableAdd($event, column)"
      @end="$emit('change')"
    >
      <template #item="{ element, index: tableIndex }">
        <div
          v-if="column.children.column.length > 0"
          class="widget-form-table__item"
          :class="{
            active: isShowButton(element, false),
            required: element.required
          }"
          :style="{
            minWidth: element.width ? `${element.width}px` : childrenWidth,
            width: element.width ? `${element.width}px` : childrenWidth
          }"
          @click.stop="handleWidgetTableSelect(element)"
        >
          <el-table :data="[element]" border>
            <el-table-column
              :prop="element.prop"
              :label="element.label"
              :align="column.children.align"
              :header-align="column.children.headerAlign"
            >
              <widget-form-item :item="element" :params="column.params" />
            </el-table-column>
          </el-table>
          <div>
            <el-button
              title="删除"
              @click.stop="handleWidgetTableDelete(column, tableIndex)"
              class="widget-table-action-delete"
              v-if="isShowButton(element, false)"
              circle
              plain
              size="default"
              type="danger"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
            <el-button
              title="复制"
              @click.stop="handleWidgetTableClone(column, tableIndex)"
              class="widget-table-action-clone"
              v-if="isShowButton(element, false)"
              circle
              plain
              size="default"
              type="primary"
            >
              <el-icon><DocumentCopy /></el-icon>
            </el-button>
          </div>
        </div>
        <div v-else></div>
      </template>
    </draggable>
    <el-button
      title="删除"
      @click.stop="handleWidgetDelete(index)"
      class="widget-action-delete"
      v-if="isShowButton(column, true)"
      circle
      plain
      size="default"
      type="danger"
    >
      <el-icon><Delete /></el-icon>
    </el-button>
    <el-button
      title="清空"
      @click.stop="handleWidgetClear(index)"
      class="widget-action-clear"
      v-if="isShowButton(column, true)"
      circle
      plain
      size="default"
      type="warning"
    >
      <el-icon><Brush /></el-icon>
    </el-button>
    <el-button
      title="复制"
      @click.stop="handleWidgetCloneTable(index)"
      class="widget-action-clone"
      v-if="isShowButton(column, true)"
      circle
      plain
      size="default"
      type="primary"
    >
      <el-icon><DocumentCopy /></el-icon>
    </el-button>
    <el-button
      title="生成"
      @click.stop="handleOpenGenFields"
      class="widget-action-generate"
      v-if="isShowButton(column, true)"
      circle
      plain
      size="default"
      type="success"
    >
      <el-icon><Setting /></el-icon>
    </el-button>

    <drag-dialog title="字段生成" v-model="showGenFields">
      <el-tree
        v-if="showGenFields"
        ref="fieldTree"
        :data="attrList" 
        show-checkbox 
        node-key="entityId" 
        :props="treeProps" 
        check-on-click-node 
        style="max-height: 600px; 
        overflow: auto;"
      />
      <template #footer>
        <dialog-footer @ok="handleGenerateFields" @cancel="cancelGenerateFields" />
      </template>
    </drag-dialog>
  </div>
</template>
<script>
import WidgetFormItem from './WidgetFormItem.vue'
import draggable from 'vuedraggable'
import { randomString } from '@/utils/zmids'
import paragraphConfig from '@code/components/anvil-code-low-common/components/paragraph/paragraphAttr'
import { generateValidUuid } from '@code/components/anvil-code-low-common/utils/common-methods'
import { cloneDeep } from 'lodash-es'

export default {
  name: 'WidgetFormTable',
  components: { WidgetFormItem, draggable },
  props: {
    data: {
      type: Object,
      default: () => {}
    },
    column: {
      type: Object,
      default: () => {}
    },
    select: {
      type: Object,
      default: () => {}
    },
    index: {
      type: Number,
      default: 0
    },
    attrList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      selectWidget: this.select,
      localData: {},
      showGenFields: false,
      treeProps:{
        children: 'childList',
        label: 'entityDescName'
      },
    }
  },
  computed: {
    childrenWidth() {
      // return this.column.children.arrangeType == 'vertical' ? '80%' : '30%'
      return '80%'
    }
  },
  watch: {
    select(val) {
      this.selectWidget = val
    },
    selectWidget: {
      handler(val) {
        this.$emit('update:select', val)
      },
      deep: true
    },
    data: {
      handler(newVal) {
        if (newVal) {
          this.localData = newVal
        }
      },
      deep: true,
      immediate: true
    },
    localData: {
      handler(newVal) {
        this.$emit('update:data', newVal)
      },
      deep: true
    }
  },
  methods: {
    handleSelectWidget(index) {
      this.selectWidget = this.localData.column[index]
    },
    handleWidgetClear(index) {
      this.localData.column[index].children.column = []
      this.selectWidget = this.localData.column[index]
      this.$emit('change')
    },
    handleWidgetDelete(index) {
      if (this.localData.column.length - 1 === index) {
        if (index === 0) this.selectWidget = {}
        else this.handleSelectWidget(index - 1)
      } else this.handleSelectWidget(index + 1)

      this.$nextTick(() => {
        this.localData.column.splice(index, 1)
        this.$emit('change')
      })
    },
    handleWidgetCloneTable(index) {
      let cloneData = this.deepClone(this.localData.column[index])

      cloneData.isAllowEdit = cloneData.isAllowEdit ? 'Y' : undefined
      cloneData.uuid = generateValidUuid()
      cloneData.prop = cloneData.uuid

      // cloneData.prop = 'a' + Date.now() + Math.ceil(Math.random() * 99999)
      // cloneData.children.column.forEach((t) => {
      //   t.prop = 'a' + Date.now() + Math.ceil(Math.random() * 99999)
      // })
      this.localData.column.splice(index + 1, 0, cloneData)
      this.$nextTick(() => {
        this.handleSelectWidget(index + 1)
        this.$emit('change')
      })
    },
    handleWidgetTableAdd(evt, column) {
      let newIndex = evt.newIndex
      const item = evt.item

      if (newIndex == 1 && newIndex > column.children.column.length - 1) newIndex = 0
      if (['子表单', '分组'].includes(item.textContent)) {
        column.children.column.splice(newIndex, 1)
        return
      }

      const data = this.deepClone(column.children.column[newIndex])
      // if (!data.prop) data.prop = 'a' + Date.now() + Math.ceil(Math.random() * 99999)
      data.subfield = true
      // 给子表单里的每一个组件增加父级标识
      data.parentName = column.prop
      delete data.icon
      column.children.column[newIndex] = { ...data }
      // this.$set(column.children.column, newIndex, { ...data })
      this.selectWidget = column.children.column[newIndex]
      this.$emit('change')
    },
    handleWidgetTableSelect(data) {
      this.selectWidget = data
    },
    handleWidgetTableClone(column, index) {
      const cloneData = this.deepClone(column.children.column[index])

      cloneData.isAllowEdit = cloneData.isAllowEdit ? 'Y' : undefined
      cloneData.uuid = generateValidUuid()
      cloneData.prop = cloneData.uuid

      column.children.column.splice(index + 1, 0, cloneData)
      // this.$set(column.children.column, column.children.column.length, {
      //   ...data
      // })
      this.$nextTick(() => {
        this.selectWidget = column.children.column[column.children.column.length - 1]
        this.$emit('change')
      })
    },
    handleWidgetTableDelete(column, index) {
      if (column.children.column.length - 1 == index) {
        if (index == 0) this.selectWidget = column
        else this.selectWidget = column.children.column[index - 1]
      } else this.selectWidget = column.children.column[index + 1]
      this.$nextTick(() => {
        column.children.column.splice(index, 1)
        this.$emit('change')
      })
    },
    isShowButton(column, isMain) {
      // 判断当前选中组件是否为子组件，区分主从表的同名组件
      return (
        this.selectWidget.prop == column.prop && !!(isMain ? true : this.selectWidget.parentName)
      )
    },
    handleOpenGenFields(){
      this.showGenFields = true
    },
    // 根据选择的实体字段生成内部组件字段
    handleGenerateFields(){
      const curSelectFields = this.$refs.fieldTree.getCheckedNodes(true)
      // 根据所选择的实体字段生成新的组件数据结构,默认生成文本提示组件类型
      const newFieldCols = curSelectFields.map((f)=>{
        const field = cloneDeep(paragraphConfig)
        field.parentName = this.localData.column[this.index].prop
        field.label = f.entityDesc
        field.prop = f.entityName
        field.uuid = generateValidUuid()
        return field
      })
      this.localData.column[this.index].children.column = cloneDeep(newFieldCols)
      this.cancelGenerateFields()
    },
    cancelGenerateFields(){
      this.showGenFields = false
    }
  }
}
</script>
<style lang="scss">
.vertical {
  display: block !important;
}
</style>
